package com.xiaochen.sjzremind.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xc
 * @date 2025/10/09/20:50
 * @desc 数据处理类
 */
@Slf4j
public class DataUtil {

    private static final String[][] aaa = {
            {"=", "*|"}, {"1", "aa|a"}, {"2", "ab|a"}, {"3", "ba|a"},
            {"4", "t|tc"}, {"5", "t|ts"}, {"8", "r|oq"}, {"9", "f|oz"}, {"0", "j|rz"}
    };

    private static final String ILLEGAL_ACCESS_WARNING_1 = "私自使用，后果自负！我方保留起诉权利！";
    private static final String ILLEGAL_ACCESS_WARNING_2 = "非法侵入计算机信息系统罪,我方公司保留报警和起诉权利";


    public static String generateSignature(String id,long timestamp) throws NoSuchAlgorithmException {
        // 生成第一个MD5哈希
        String first = md5("id=" + id + timestamp);
        // 生成第二个MD5哈希
        String second = md5(timestamp + first + ILLEGAL_ACCESS_WARNING_1);
        return second;
    }

    public static Map<String, Object> disengageSignature(String encryptedData) {
        try {
            String decryptedData = aesCbcDecrypt(encryptedData);
            if (decryptedData == null || decryptedData.isEmpty()) {
                return new HashMap<>();
            }

            if (decryptedData.startsWith(ILLEGAL_ACCESS_WARNING_2)) {
                decryptedData = decryptedData.replace(ILLEGAL_ACCESS_WARNING_2, "");
                decryptedData = urlDecBase64(decryptedData);
            }

            ObjectMapper mapper = new ObjectMapper();
            return mapper.readValue(decryptedData, Map.class);
        } catch (Exception e) {
            return new HashMap<>();
        }
    }

    private static String aesCbcDecrypt(String encryptedData) {
        try {
            byte[] encryptedBytes = Base64.getDecoder().decode(encryptedData);

            // 生成密钥: MD5("https://orzice.com")
            String keyStr = md5("https://orzice.com");
            byte[] keyBytes = keyStr.getBytes(StandardCharsets.UTF_8);

            // IV向量
            String ivStr = "cAnByjySGOstUlMc";
            if (ivStr.length() < 16) {
                ivStr = String.format("%-16s", ivStr).replace(' ', '\0');
            }
            byte[] ivBytes = ivStr.substring(0, 16).getBytes(StandardCharsets.UTF_8);

            SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
            IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);

            byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
            return new String(decryptedBytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            return "";
        }
    }

    private static String urlDecBase64(String input) {
        // 替换字符映射
        for (String[] mapping : aaa) {
            input = input.replace(mapping[1], mapping[0]);
        }

        byte[] decodedBytes = Base64.getDecoder().decode(input);
        return new String(decodedBytes, StandardCharsets.UTF_8);
    }

    private static String md5(String input) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] hashBytes = md.digest(input.getBytes());
        StringBuilder sb = new StringBuilder();
        for (byte b : hashBytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }

    public static void main(String[] args) {
//        String encryptedData = "+olt8G1xtTvOPQYLRbyup1KG9SEoVQl+qNbbDJw8MSRTl0xf8JZ89cuhgwgiSNgXxgfwdCTzm79T9GlW28b4OMqgxscpva5K7J4gsUonvsoxbzvDH95IHrbnrv32xW6lVhDnzzbrxunAW8newbRVPzvIalMx5tJ+EJyj/D3X9ANPCPGh4m3jVQ0LyvMHyRzjx1JoNN/RJb3xfPYeZ8o6OysoGyPrnsahIe9GUEOlB0Yd//fWhCVoUYX3AKSaa8l0Ool6f+aStwi/9FtbVLbbIrIiRfLJYit0FGIj19UnXw2SQ6HglKoFJota3yj7Xkia8oB1gAm1Z2P4fdaPNaF8S7HfEJvD88sCbVZpl5SFmHsa4eRrXgHigYAHHTQgHq9IwmmATs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riqjSDGZfYD+v7B5bjYOSKqA6TRoLSIbCEGLCzirZJzDcqaYXH7OBgKNrTv0osJ6IEWkriEolKBShRH06S1/UPzziI9q66r40EFvBEKhsXOne1Z0eZHwFktLZw8Xca17mbur33LV/XUd07DhnL7czHtprxVyqLAmMzRXH81nF2O+MyLk3z5brIiYi3+zV4wDgFjwncuRn6AtAnRDPcKLjyL53OtL1fqFsqmda0IWwglZin6sD6sYR+FnLZN4360dVkKqIFF5w/6ktbhEl2ijNwt8AWbryp44xibPqzByykccPkTH6HDBIpu0su9PsE09nels6ptAnYON3Yhb8QPwkLh0jIf5cq0CfKsRoZd7kKLhTrrHm49Xz2DAkQzL7DOysGfnSRptGvSxs8dcb8tsYL72opWhZeEuYEOzillNEHEpwxJymIRDuqwUkOf9dn7R6ZANsE77fHsMJkT+dw2cxGOCTqiYY3KRf60WvZLvVkpN5+sVSOaoHrnD0UTLubInzWNQ93kO56pEEE8c0dGN0ulPiR1w8g==";
//        Map<String, Object> objectMap = DataUtil.disengageSignature(encryptedData);
//        log.info("map:{}", objectMap);
    }
}
